from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import memcache

import common
import observer

class ConnectedHandler(common.BaseRequestHandler):
    def post(self):
        client_id = self.request.get('from')
        user_channels = memcache.get(common.USER_CHANNEL)
        if user_channels:
            user, channel_name = user_channels.get(client_id)
            observable = observer.Observable(channel_name)
            response = {'event': 'add_user',
                'args': {'user': user}}
            observable.notify_observers(self.json_format(response))


class DisconnectedHandler(common.BaseRequestHandler):
    def post(self):
        client_id = self.request.get('from')
        user_channels = memcache.get(common.USER_CHANNEL)
        if user_channels:
            user, channel_name = user_channels.get(client_id)
            available_users = memcache.get(channel_name)
            # del available_users[user]
            # memcache.set(channel_name, available_users, 30*60)
            observable = observer.Observable(channel_name)
            response = {'event': 'remove_user',
                'args': {'user': user}}
            observable.notify_observers(self.json_format(response))

application = webapp.WSGIApplication(
                                     [
                                     ('/_ah/channel/connected/', ConnectedHandler),
                                     ('/_ah/channel/disconnected/', DisconnectedHandler)
                                     ],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
